package com.atguigu.srb.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

@Configuration
//@Component
public class GatewayConfig {
    //网关：CorsWebFilter、微服务：//@CrossOrigin
    //将gateway提供的 配置跨域的filter注入到容器中 会自动生效
    @Bean
    public CorsWebFilter corsWebFilter(){
        //后端服务器资源较多：哪些允许跨域访问、哪些不允许、允许跨域请求以哪种请求方式/携带哪些头/cookie...来访问
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        //一个跨域配置
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedHeader("*"); //允许携带所有请求头跨域访问
        config.addAllowedMethod("*"); //允许所有请求方式跨域访问
        config.addAllowedOrigin("*"); //允许哪些组织跨域访问(前端服务器)
        config.setAllowCredentials(true); //允许携带cookie跨域访问
        //使用指定路径 给他配置跨域参数    /** 匹配所有路径
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }
}
